package com.tanhua.api.mongo;

import com.tanhua.mongo.UserLocation;
import com.tanhua.vo.UserLocationVo;
import org.springframework.data.geo.Circle;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void toAddr(double x_latitude, double y_longitude, String addrStr, Long id) {
        // 根据当前登录用户的id查询当前登录用户是否做过上报
        Query query = new Query(Criteria.where("userId").is(id));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if(userLocation==null){
            // 没有--mongo做新增
            userLocation=new UserLocation();
            userLocation.setUserId(id);
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());

            //GeoJsonPoint：mongodb提供专门用来提供经纬度封装的对象
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(y_longitude,x_latitude);
            userLocation.setLocation(geoJsonPoint);

            mongoTemplate.insert(userLocation);

        }else{
            // 有 --mongo做修改
            Update update = new Update();
            update.set("address",addrStr);
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(y_longitude,x_latitude);
            update.set("location",geoJsonPoint);
            update.set("updated",System.currentTimeMillis());
            mongoTemplate.upsert(query, update, UserLocation.class);
        }



    }

    @Override
    public List<UserLocationVo> search(String gender, Integer distance, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query,UserLocation.class);
        //以自身的坐标为起点 按照指定的距离 做圆半径的搜索
        Distance dist = new Distance(distance, Metrics.KILOMETERS);
        Circle circle = new Circle(userLocation.getLocation(), dist);
        //做圆半径的坐标搜索
        Query query1 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query1, UserLocation.class);
        //自己创建一个转换对象（数据给转换对象）  UserLocation--geoJsonPoint（没有实现序列化）
        List<UserLocationVo> voList = UserLocationVo.formatToList(userLocationList);
        //返回转换对象
        return voList;
    }
}
